563. 二叉树的坡度
为保证权益,题目请参考 563. 二叉树的坡度(From LeetCode).
解决方案1
Python
python
# 563. 二叉树的坡度
# https://leetcode-cn.com/problems/binary-tree-tilt/
################################################################################
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def findTilt(self, root: TreeNode) -> int:
self.ans = 0
def dfs(root: TreeNode):
if root is None:
return 0
l = dfs(root.left)
r = dfs(root.right)
self.ans += abs(r - l)
return l + r + root.val
dfs(root)
return self.ans
################################################################################
if __name__ == "__main__":
solution = Solution()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35